<?php
/**
 * 历史数据生成采购单和付款单
 * @author angl
 */
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

$db = init_db();
$last_id = 0;
$counter = 0;

//id	int(11) 自动增量	自增ID
//order_id	int(11)	拍单ID
//collection_id	int(11)	收款ID
//payment_type	smallint(3)	收款类型
//createtime	datetime	创建时间
//车商付款状态（0未确认 ,1未付款，2，待核实 3，已付款 4 , 锁定 5,收款失败)
while (true) {
    $db->join("order o", "pl.order_id=o.order_id", "INNER");
    $list = $db->where("pl.pl_id", $last_id, ">")->get('proceeds_log pl', 2000, "pl.*,o.dealer_pay_status,o.status order_status");

    if (empty($list)) {
        logUtil($counter . "条数据处理完成", 'INFO');
        exit;
    }

    //循环处理
    foreach ($list as $item) {
        $data = [];
        $data['payment_type'] = 1;
        $data['payment_method'] = 1;
        if ($item['dealer_pay_status'] == 1) {
            $data['status'] = 0;
            $data['amount'] = $db->where('order_id', $item['order_id'])->getValue("order_fee", "final_price");
            $data['emp_id'] = 0;
            $data['emp_name'] = '';
            $data['create_time'] = $item['createtime'];
        } elseif ($item['dealer_pay_status'] == 3) {
            $data['status'] = 1;
            $data['amount'] = $item['amount'];
            $data['emp_id'] = $item['emp_id'];
            $data['emp_name'] = $db->where("emp_id", $item['emp_id'])->getValue("employee", "real_name");
            $data['create_time'] = $item['createtime'];
            $data['update_time'] = $item['pay_time'];
        } elseif ($item['dealer_pay_status'] == 4) {
            $data['status'] = 2;
            $data['amount'] = $db->where('order_id', $item['order_id'])->getValue("order_fee", "final_price");
            $data['emp_id'] = $item['emp_id'];
            $data['emp_name'] = $db->where("emp_id", $item['emp_id'])->getValue("employee", "real_name");
            $data['create_time'] = $item['createtime'];
            $data['update_time'] = $item['violatetime'];
        } elseif ($item['dealer_pay_status'] == 5) {
            $data['status'] = 3;
            $data['amount'] = $db->where('order_id', $item['order_id'])->getValue("order_fee", "final_price");
            $data['emp_id'] = $item['emp_id'];
            $data['emp_name'] = $db->where("emp_id", $item['emp_id'])->getValue("employee", "real_name");
            $data['create_time'] = $item['createtime'];
            $data['update_time'] = $item['violatetime'];
        }else{
            continue;
        }
        genCollection($data,$item['order_id']);
        $last_id = $item['pl_id'];
        $counter++;
    }
}

echo "完成";
die();

function genCollection($data,$order_id)
{
    global $db;
    $db->startTransaction();
    $data['collection_no'] = genBillsNo("SK", 1, $data['create_time']);
    $collectionId = $db->insert('collection', $data);
    if (!$collectionId) {
        logUtil("[genCollection] {$data['order_id']} 生成收款单失败", "ERR");
        $db->rollback();
    }
    $relation = [
        'order_id' => $order_id,
        'collection_id' => $collectionId,
        'payment_type' => $data['payment_type'],
        'createtime' => $data['create_time'],
    ];
    $res = $db->insert("order_collections", $relation);
    if (!$res) {
        logUtil("{$order_id} 生成拍单收款单关系失败", "ERR");
        $db->rollback();
    }
    logUtil($order_id. "生成收款单成功","ERR");
    $db->commit();
    return $collectionId;
}

/**
 * 产生固定长度的随机字符串
 * @param $len
 * @param null $chars
 * @return string
 */
function genRandomChars($len, $chars = null)
{
    if (is_null($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

/**
 * 产生一个四位的随机字符串
 * @return string
 */
function gen4Chars()
{
    $strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $numbers = "0123456789";
    $randomString = genRandomChars(3);
    if (ctype_digit($randomString)) {
        $randomString = $randomString . genRandomChars(1, $strChars);
    } elseif (ctype_alpha($randomString)) {
        $randomString = $randomString . genRandomChars(1, $numbers);
    } else {
        $randomString = $randomString . genRandomChars(1);
    }
    return $randomString;
}

/**
 * 产生一个单据编号
 * @param $type
 * @param $subType
 * @param $date
 * @return string
 */
function genBillsNo($type, $subType, $date)
{
    global $db;
    if ($subType < 10) $subType = "0" . $subType;
    $date = date("Ymd", strtotime($date));
    $orderNo = $type . $subType . $date . gen4Chars();
    if ($type == 'SK') { //如果是采购单
        $data = $db->where('collection_no', $orderNo)->getOne('collection');
        if ($data) {
            return genBillsNo($type, $subType, $date);
        }
    }
    return $orderNo;
}






